<template>
    <div class="search-song">
      <song-list :songList="currentSongList"></song-list>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, watch, onMounted } from "vue";
  import { useStore } from "vuex";
  import SongList from "@/components/SongList.vue";
  import { HttpManager } from "@/api";
  import {ElMessage} from "element-plus";
  import { useRouter } from "vue-router";
  
  const store = useStore();
  const route = useRouter();
  const currentSongList = ref([]); // 存放的音乐
  const searchWord = computed(() => store.getters.searchWord);
  // 监听搜索关键词的变化，当搜索关键词改变时，调用搜索音乐的函数
  watch(searchWord, (value) => {
    searchSong(value);
  });
  
  // 搜索音乐
  async function searchSong(value) {  
    if (!value) {
      currentSongList.value = [];
      return;
    }
    const result = (await HttpManager.getSongOfSongName(value)) as ResponseBody;
    if (!result.data.length) {
      currentSongList.value = [];
      ElMessage({
        message: "暂时没有相关歌曲",
        type: "warning",
      });
    } else {
      currentSongList.value = result.data;
    }
  }
  
  // 组件挂载时，尝试从路由查询参数中获取关键词并进行歌曲搜索
  onMounted(() => {
    searchSong(route.currentRoute.value.query.keywords);
  });
  </script>